package sdk.webview.fmc.com.fmcsdk.activity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.bean.NFCResult;
import sdk.webview.fmc.com.fmcsdk.check.NfcCodeEvent;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelperClick;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.URLEncodeUtils;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.nfc.ParsedNFCRecord;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;
import sdk.webview.fmc.com.fmcsdk.view.GifView;

public class H5ForNfcActivity extends BaseActivity {

    TextView tvFlag;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    public static final String SCAN_RESULT = "scan_result";
    TitleBar titlebar;
    private boolean scanToOpenNfc;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_h5_for_nfc;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
         tvFlag = (TextView) findViewById(R.id.tv_flag);
//        ImageView iv_gif = (ImageView) findViewById(R.id.iv_gif);
//        Glide.with(context).load(R.drawable.nfc).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                .into(iv_gif);
        GifView gifImageView = (GifView) findViewById(R.id.iv_gif);
        gifImageView.setGifResource(R.drawable.nfc);
        titlebar.setTitle(getString(R.string.nfc_scan));
        scanToOpenNfc = getIntent().getBooleanExtra(Constant.SCAN_TO_OPEN_NFC, false);
        setNFCAdapter();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    //设置NFC基本配置
    private void setNFCAdapter() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[]{ndef,};
        // 根据标签类型设置
        mTechLists = new String[][]{new String[]{NfcA.class.getName()}};
        checkNFCFunction();
    }

    //检查是否具有NFC功能和是否开启了NFC
    private void checkNFCFunction() {
        if (mNfcAdapter != null) {
            if (!mNfcAdapter.isEnabled()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.remind));
                builder.setMessage(getString(R.string.want_to_nfc));
                builder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                                startActivity(setnfc);
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();

            }
        } else {
            tvFlag.setText(getString(R.string.device_cnot_supported_nfc));
        }

    }


    @Override
    protected void onResume() {
        // TODO 自动生成的方法存根
        super.onResume();
        enableForegroundDispatch();
    }

    private void enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        disableForegroundDispatch();
    }

    private void disableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
if(!FastClickHelperClick.isFastClick())return;
        Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (messages != null && messages.length > 0) {
            NdefMessage message = (NdefMessage) messages[0];
            String result = ParsedNFCRecord.readTag(message);
            //老系统招商项目等NFC返回值开头带有0和1的处理方法
            //            String content = ParsedNFCRecord.readTag(message);
//            NFCEntity entity = new NFCEntity().parse(content);
//            String result=entity.getNumber();
            XLog.i(result);
            if (result.contains("id=") && result.contains("ver=")) {
                result = URLEncodeUtils.decoder(result.substring(result.indexOf("id=") + 3, result.lastIndexOf("&ver=")));
            }
//            Intent intents = new Intent();
//            intents.putExtra(Constant.NFC_RESULT, result);
//            setResult(RESULT_OK, intents);
            NFCResult nfcResult = new NFCResult();
            nfcResult.setCode(result);
            nfcResult.setScanToOpenNfc(scanToOpenNfc);
            RxBus.getDefault().send(nfcResult);
            EventBus.getDefault().post(new NfcCodeEvent(result,getIntent().getStringExtra("from")));
            finish();
        }
    }


}